import SmallRank = rank.SmallRank;

class Main extends egret.DisplayObjectContainer {

    public postData: any;

    public static readonly Hide: number = 0;
    public static readonly Show: number = 1;
    public static readonly Submit: number = 2;
    public static readonly Show_Game_Over_Rank: number = 4;
    public static readonly SHOW_GROUP_RANK: number = 5;

    public static readonly Pk_Friends: number = 10002;

    public static readonly Get_Friends_Pk_Data: number = 10003;

    public static readonly Hide_Pk_Friends: number = 10004;

    public static readonly Only_Submit_Score: number = 10005;

    public static readonly PREV_PAGE: number = 10006;

    public static readonly NEXT_PAGE: number = 10007;

    public static readonly SHOW_LIMIT_TIME_RANK: number = 10008;

    public static readonly SHOW_SMALL_RANK: number = 10009;

    public static readonly HIDE_SMALL_RANK: number = 10010;

    public static readonly CREATE_POSTER: number = 10011;

    public static readonly HIDE_POSTER: number = 10012;

    public static readonly GET_MY_AVATAR: number = 10013;

    private commonRank: rank.CommonRank;

    private command: number;

    private myScore: number = 0;

    public static openid: string;

    private pkFriend: pk.PkFriend;

    private recentRank: rank.RecentRank;

    private upArr = [];

    public static readonly MEDALS: Array<string> = ["", "初窥门径", "略有成就", "炉火纯青", "登峰造极", "超凡入圣"];

    public static instance: Main;

    public constructor() {
        super();
        Main.instance = this;
        let that = this;
        let newNext = [];
        let array = null;
        this.loadImage("resource/assets/GameRes/game/sheet/rank.png");
        
        wx.onMessage(data => {            
            egret.log("rank command id:", data.command);
            that.command = data.command;
            if (that.command != Main.Pk_Friends) {
                that.postData = data;
            }
            Main.openid = data.openid || "";

            if (this.pkFriend != null) {
                this.pkFriend.visible = false;
            }


            egret.log("data.command:", data.command);
            switch (data.command) {
                case 100:
                    that.hideAllRanks()
                
                    if (that.recentRank) {
                        that.removeChildren();
                        that.recentRank = null;
                    }
                    let sharedCanvas = wx.getSharedCanvas()
                    //绘制距离上一名距离
                    wx.getFriendCloudStorage({
                        keyList: data.keyList,
                        success: res => {
                            array = res.data
                            console.log(array)
                            if (array.length > 1) {
                                res.data.forEach(item => {
                                    if(item.KVDataList.length == 0){
                                        item.KVDataList.push({key: "score", value: "0"})
                                        item.score = 0
                                    }else{
                                        item.score = Number(item.KVDataList[0].value)
                                    }
                                    
                                })
                                let aaa = res.data.sort(that.compare('score'))
                                let info = aaa[0]
                                this.upArr = []
                                that.upArr.push(info)
                                that.recentRank = new rank.RecentRank(info);
                                that.addChild(that.recentRank);
                                that.recentRank.visible = true;
                            }
                        },
                        fail: err => {
                            console.log(err);
                        },
                        complete: () => {}
                    });
                    break
                case 101:
                    let nowScore = Number(data.score)
                    let nextItem
                    if (array.length > 1) {
                        nextItem = array.filter(item => {
                            return Number(item.KVDataList[0].value) >= nowScore
                        })
                        nextItem.forEach(item => {
                            item.score = Number(item.KVDataList[0].value)
                        })
                        newNext = nextItem.sort(that.compare('score'))
                        let info = newNext[0]
                        that.upArr.push(info)
                        if (that.upArr[0] === that.upArr[1]) {
                            that.upArr = that.upArr.slice(0, 1)
                        } else {
                            that.removeChild(that.recentRank);
                            console.log(that.upArr)
                            that.upArr = that.upArr.slice(1)
                            console.log(that.upArr)
                            that.recentRank = new rank.RecentRank(that.upArr[0]);
                            that.addChild(that.recentRank);
                        }
                    }
                    break



                case Main.Submit:
                    if(data.scoreData.length > 0) {
                        that.myScore = parseInt(data.scoreData[0].value);
                    }
                    that.submit(data.scoreData);
                    break;
                case Main.Hide:
                    // that.hideRank();
                    that.hideAllRanks();
                    break;
                case Main.Show:
                    this.hideAllRanks()
                    that.getFriendRankData();
                    break;
                case Main.Show_Game_Over_Rank:
                    that.getFriendRankData();
                    break;
                case Main.Pk_Friends:
                    that.pkMyFriend(data.score);
                    break;
                case Main.Get_Friends_Pk_Data:
                    break;
                case Main.SHOW_GROUP_RANK:
                    that.getGroupRank();
                    break;
                case Main.Hide_Pk_Friends:
                    that.hidePk();
                    break;
                case Main.Only_Submit_Score:
                    this.onlySubmit(data.scoreData);
                    break;
                case Main.PREV_PAGE:
                    this.navigatePage(Main.PREV_PAGE);
                    break;
                case Main.NEXT_PAGE:
                    this.navigatePage(Main.NEXT_PAGE);
                    break;
                case Main.SHOW_LIMIT_TIME_RANK:
                    that.onShowLimitTimeRank();
                    break;
                case Main.SHOW_SMALL_RANK:
                    this.hideAllRanks()
                    that.onShowSmallRank();
                    break;
                case Main.HIDE_SMALL_RANK:
                    that.hideSmallRank();
                    break;
                case Main.CREATE_POSTER:
                    that.createPoster();
                    break;
                case Main.HIDE_POSTER:
                    that.hidePoster();
                    break;
                case Main.GET_MY_AVATAR:
                    that.getMyAvatar();
                    break;
            }
        });
    }

    private compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
        }
    }

    private isHeadImgLoaded: boolean = false;

    private getMyAvatar(): void {
        if (this.isHeadImgLoaded) {
            return;
        }
        let avatarURL: string = this.postData.extra.headurl;
        let imageLoader = new egret.ImageLoader();
        imageLoader.addEventListener(egret.Event.COMPLETE, this.loadCompleteHandler, this);
        imageLoader.load(avatarURL);
    }

    public headImg: egret.Bitmap = new egret.Bitmap();

    private loadCompleteHandler(event: egret.Event): void {
        this.isHeadImgLoaded = true;
        let imageLoader = <egret.ImageLoader>event.currentTarget;
        imageLoader.removeEventListener(egret.Event.COMPLETE, this.loadCompleteHandler, this);
        let texture = new egret.Texture();
        texture._setBitmapData(imageLoader.data);
        this.headImg.$setTexture(texture);
    }

    private poster: rank.CreatePoster;

    private createPoster(): void {
        helper.DisplayManager.remove(this.poster);
        this.poster = new rank.CreatePoster();
        this.poster.level = this.postData.level;
        this.poster.percent = this.postData.percent;
        this.poster.nick = this.postData.nick;
        this.poster.update();
        this.addChild(this.poster);
    }

    private hidePoster(): void {
        helper.DisplayManager.remove(this.poster);
    }

    private hideSmallRank(): void {
        console.log('hideSmallRank')
        helper.UtilsManager.remove(this.smallRank);
    }

    private onShowSmallRank(): void {
        egret.log("显示小排行");
        let that = this;
        wx.getFriendCloudStorage({
            keyList: ['score'],
            success: res => {
                that.socialData = res.data;
                that.showSmallRank(res);
            },
            fail: err => {
                console.log(err);
            },
            complete: () => {
            }
        });
    }

    private showSmallRank(res): void {
        this.hideAllRanks();
        this.rankData = res.data;
        let infos: Array<rank.ScoreItem> = Main.format(this.rankData);
        if (this.smallRank == null) {
            this.smallRank = new rank.SmallRank();
        }
        this.addChild(this.smallRank);
        for (let i: number = 0; i < infos.length; i++) {
            let info = infos[i];
            info.rankNb = i + 1;
        }
        this.smallRank.update(infos);
    }

    private smallRank: SmallRank;

    private onShowLimitTimeRank(): void {
        let data = this.postData;
        egret.log("data.keyList:", data.keyList);
        let that = this;
        wx.getFriendCloudStorage({
            keyList: ['limit_time_score'],
            success: res => {
                console.log("res", res);
                that.socialData = res.data;
                that.showLimitTimeRank(res);
            },
            fail: err => {
                console.log(err);
            },
            complete: () => {
            }
        });
    }

    private navigatePage(command: number): void {
        if (this.currentRank != null) {
            switch (command) {
                case Main.PREV_PAGE:
                    this.currentRank.onPrevPage();
                    break;
                case Main.NEXT_PAGE:
                    this.currentRank.onNextPage();
                    break;
            }
        }

    }

    private hidePk(): void {
        egret.log("隐藏hidePk()");
        if (this.pkFriend != null) {
            this.pkFriend.visible = false;
        }
    }

    private pkMyFriend(score: number): void {
        this.hideAllRanks();
        if (this.pkFriend == null) {
            this.pkFriend = new pk.PkFriend();
            this.addChild(this.pkFriend);
        }
        if (this.pkFriend.parent == null) {
            this.addChild(this.pkFriend);
        }
        egret.log("显示朋友PK界面");
        this.pkFriend.visible = true;
        this.pkFriend.pk(score);
    }

    private getFriendRankData() {
        let that = this;
        let data = that.postData;
        wx.getFriendCloudStorage({
            keyList: data.keyList,
            success: res => {
                console.log("res", res);
                that.socialData = res.data;
                that.showRank(res);
            },
            fail: err => {
                console.log(err);
            },
            complete: () => {
            }
        });
    }

    private getGroupRank() {
        let that = this;
        let data = that.postData;
        egret.log("开始显示群排行");
        egret.log("群分享ticket:", data.scoreData[0]);
        wx.getGroupCloudStorage({
            shareTicket: data.scoreData[0],
            keyList: data.keyList,
            success: res => {
                egret.log("群排行数据:", res);
                that.socialData = res.data;
                that.showRank(res);
            },
            fail: err => {
                console.log("开始显示群排行失败:", err);
            },
            complete: (res) => {
                egret.log("群排行数据:", res);
            }
        });
    }

    private onlySubmit(data: any): void {
        let that = this;
        wx.setUserCloudStorage({
            KVDataList: data,
            success: function (res) {
                console.log("设置数据成功", res);
            },
            fail: function (res) {
                console.log("设置数据失败", res);
            },
            complete: function (res) {
                console.log("设置数据完成", res);
            }
        });
    }

    private submit(data: any, isShowRank: boolean = true): void {
        let that = this;
        wx.setUserCloudStorage({
            KVDataList: data,
            success: function (res) {
                console.log("设置数据成功", res);
            },
            fail: function (res) {
                console.log("设置数据失败", res);
            },
            complete: function (res) {
                console.log("设置数据完成", res);
                // if (isShowRank) {
                //     that.getFriendRankData();
                // }
            }
        });
    }

    private rankData = [
        {openid: '', avatarUrl: '', nickname: 'peony', KVDataList: [{value: "100"}]}
    ];

    private limitTimeRank: rank.CommonRank;

    private showLimitTimeRank(res): void {
        this.hideAllRanks();
        this.rankData = res.data;
        let infos: Array<rank.ScoreItem> = Main.formatLimitTimeRank(this.rankData);
        if (this.limitTimeRank == null) {
            this.limitTimeRank = new rank.CommonRank();
        }
        this.currentRank = this.limitTimeRank;
        this.limitTimeRank.reset();
        this.addChild(this.limitTimeRank);
        for (let i: number = 0; i < infos.length; i++) {
            let info = infos[i];
            info.rankNb = i + 1;
        }
        this.limitTimeRank.update(infos, this.command);
    }

    //desc表示降序
    public static formatLimitTimeRank(friendData: Array<any>, desc: boolean = true): Array<rank.ScoreItem> {

        console.log('formatLimitTimeRank')

        let infos: Array<rank.ScoreItem> = [];
        let len: number = friendData.length;
        for (let i: number = len - 1; i >= 0; i--) {
            let data = friendData[i];
            if (data.KVDataList.length < 1) {
                friendData.splice(i, 1);
            }
        }
        let vidx: number = 0;
        if (desc) {
            friendData = friendData.sort(function (a: any, b: any) {
                return b.KVDataList[vidx].value - a.KVDataList[vidx].value;
            });
        } else {
            friendData = friendData.sort(function (a: any, b: any) {
                return a.KVDataList[vidx].value - b.KVDataList[vidx].value;
            });
        }

        friendData.forEach(function (info, idx) {
            let item = new rank.ScoreItem(info.openid,
                info.avatarUrl,
                parseInt(info.KVDataList[vidx].value),
                idx + 1,
                info.nickname);
            infos.push(item);
        });
        return infos;
    }

    private hideAllRanks(): void {
        console.log('hideAllRanks')
        helper.UtilsManager.remove(this.limitTimeRank);
        helper.UtilsManager.remove(this.commonRank);
        helper.UtilsManager.remove(this.smallRank);
        helper.UtilsManager.remove(this.poster);
        helper.UtilsManager.remove(this.recentRank);
    }


    private currentRank:rank.CommonRank;
    private showRank(res): void {
        console.log('showRank')
        this.rankData = res.data;
        let infos: Array<rank.ScoreItem> = Main.format(this.rankData);
        this.hideAllRanks();
        if (this.commonRank == null) {
            this.commonRank = new rank.CommonRank();
        }
        this.currentRank = this.commonRank;
        this.commonRank.reset();
        this.addChild(this.commonRank);
        for (let i: number = 0; i < infos.length; i++) {
            let info = infos[i];
            info.rankNb = i + 1;
        }
        this.commonRank.update(infos, this.command);
    }

    private socialData: any;

    private loadImage(url: string): void {
        let loader = new egret.ImageLoader();
        loader.once(egret.Event.COMPLETE, (event: egret.Event) => {
            egret.log("排行榜素材加载完成");
            let texture = new egret.Texture();
            texture._setBitmapData(event.currentTarget.data);
            rank.CommonRank.spriteSheet = new rank.GameSpriteSheet(texture);
        }, this);
        loader.load(url);
    }


    //desc表示降序
    public static format(friendData: any, desc: boolean = true): Array<rank.ScoreItem> {
        let infos: Array<rank.ScoreItem> = [];
        if (desc) {
            friendData = friendData.sort(function (a: any, b: any) {
                if(a.KVDataList.length == 0){
                    a.KVDataList[0] = {
                        value: 0
                    }
                }
                if(b.KVDataList.length == 0){
                    b.KVDataList[0] = {
                        value: 0
                    }
                }
                return b.KVDataList[0].value - a.KVDataList[0].value;
            });
        } else {
            friendData = friendData.sort(function (a: any, b: any) {
                return a.KVDataList[0].value - b.KVDataList[0].value;
            });
        }

        friendData.forEach(function (info, idx) {
            let item = new rank.ScoreItem(info.openid,
                info.avatarUrl,
                parseInt(info.KVDataList[0].value),
                idx + 1,
                info.nickname);
            infos.push(item);
        });
        return infos;
    }

    private hideRank(): void {
        console.log("关闭排行");
    }
}